package com.nervenets.web.controller.handler.admin.user;

import com.alibaba.fastjson.JSONObject;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.hibernate.domain.user.UserRole;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class UserRoleHandler extends SessionHandler<UserRoleParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserRoleParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getTargetUserId(), o -> {
            final User user = userDao.findByIdIgnoreRemoved(params.getTargetUserId(), User.class);
            if (null == user) return errorMessage(MessageCode.code_404, "授权的用户不存在");

            /*final User inviteUser = userDao.findByIdIgnoreRemoved(params.getInviteUserId(), User.class);
            if (null == inviteUser) return errorMessage(MessageCode.code_404, "推荐人用户不存在");*/

            try {
                JSONObject.parseObject(params.getUserRoles(), UserRole.class);
            } catch (Exception e) {
                return errorMessage(MessageCode.code_444, "权限格式不正确");
            }

            //user.setInviteUserId(params.getInviteUserId());
            user.setRole(JSONObject.parseObject(params.getUserRoles(), UserRole.class));

            userDao.saveOrUpdate(user);
            globalService.clearRedisUserStored(user.getId());

            return successMessage(user);
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
